/*
 * @Author: Leng
 * @Date: 2023-09-08 15:23:40
 * @Description: 官方文案：https://uniapp.dcloud.net.cn/api/request/request.html#request
 * @FilePath: \travelWeb\src\api\request.ts
 */
const baseURL = "1.117.192.100:9000/travel"

// 定义返参
type Data<T> = {
	code: string
	msg?: string
	data: T
}

// 封装请求
const request = <T>(options: UniApp.RequestOptions) => {
	return new Promise<Data<T>>((resolve, reject) => {
		// 获取url
		let url = options.url;
		// 请求超时
		options.timeout = 1000 * 10
		// 是否http或https开头
		const reg = /^https?/;
		// baseURL
		if (!reg.test(url)) {
			url = baseURL + url;
		}
		// 请求头
		const header = options.header || {};
		// 添加token
		header.Authorization = "Bearer " + uni.getStorageSync("token");
		// 小程序端请求头标识
		header.sourceClient = 'miniapp',
		// 公用请求头标识
		header.channel = "h5";
		// 发起网络请求
		uni.request({
			// 地址
			url,
			// 请求头
			header,
			// 请求数据
			data: options.data,
			method: options.method || "GET",
			success(res) {
				// 如果没有权限
				if (res.statusCode === 401) {
					uni.showToast({
						title: "没有权限"
					})
					reject(res);
				} else {
					resolve(res.data as Data<T>)
				}
			},
			fail(err) {
				reject(err)
			}
			// complete() {
			// 	console.log('调用结束')
			// }
		})
	})
}
// get
request.get = (url: string, config?: UniApp.RequestOptions) => {
	return request({url, method: "GET", ...config})
}
// post
request.post = <T>(url: string, data:T, config?: any) => {
	return request({url, method: "POST", data, ...config})
}

export default request